// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestThreadInfo.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Defines the TestThreadInfo type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Testing.Threading
{
    using System;
    using System.Text;
    using System.Threading;

    public class TestThreadInfo
    {
        #region Fields

        private readonly TestThreadType _threadType;
        private readonly int _managedThreadId;
        private readonly string _name;

        #endregion

        private TestThreadInfo(string name, int managedThreadId, TestThreadType threadType)
        {
            _name = name;
            _threadType = threadType;
            _managedThreadId = managedThreadId;
        }

        /// <summary>
        /// Gets or sets the id of the thread running the current test
        /// </summary>
        public static int? TestThreadId
        {
            get;
            set;
        }

        public string Name
        {
            get { return _name; }
        }

        public int ManagedThreadId
        {
            get { return _managedThreadId; }
        }

        public TestThreadType ThreadType
        {
            get { return _threadType; }
        }

        public static TestThreadInfo FromCurrentThread()
        {
            return From(Thread.CurrentThread);
        }

        public static TestThreadInfo From(Thread thread)
        {
            return new TestThreadInfo(thread.Name, thread.ManagedThreadId,
               ThreadTypeFromThread(thread));
        }

        public static TestThreadType ThreadTypeFromThread(Thread thread)
        {
            if (thread.ManagedThreadId == TestThreadId)
            {
                return TestThreadType.TestThread;
            }
            
            if (thread.IsThreadPoolThread)
            {
                return TestThreadType.ThreadPool;
            }

            if (thread.Name == AsynchronousTest.DispatcherThreadName)
            {
                return TestThreadType.TestThreadDispatcher;
            }
            return TestThreadType.Unknown;
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendFormat("Name=\"{0}\", ", _name ?? String.Empty)
               .AppendFormat("ThreadId={0}, ", _managedThreadId)
               .AppendFormat("ThreadType={0}, ", _threadType);
            return sb.ToString();
        }
    }
}